<template>
  <div class="profile-settings-page">
    <van-nav-bar
      title="个人设置"
      left-arrow
      @click-left="goBack"
      fixed
    />
    
    <div class="container">
      <!-- 个人资料部分 -->
      <div class="section-card">
        <div class="section-title">个人资料</div>
        
        <van-cell-group inset>
          <van-cell title="头像" is-link center @click="uploadAvatarAction">
            <template #right-icon>
              <img class="user-avatar" :src="userInfo.avatar || 'https://randomuser.me/api/portraits/men/32.jpg'" alt="用户头像">
            </template>
          </van-cell>
          
          <van-cell title="昵称" :value="userInfo.nickname || '未设置'" is-link @click="editField('nickname')" />
          
          <van-cell title="个性签名" is-link @click="editField('bio')">
            <template #value>
              <div class="bio-text">{{ userInfo.bio || '未设置' }}</div>
            </template>
          </van-cell>
          
          <van-cell title="性别" :value="genderText" is-link @click="openGenderPicker" />
          
          <van-cell title="生日" :value="userInfo.birthday || '未设置'" is-link @click="openDatePicker" />
        </van-cell-group>
      </div>
      
      <!-- 账户与安全部分 -->
      <div class="section-card">
        <div class="section-title">账户与安全</div>
        
        <div class="security-item">
          <div class="security-icon">
            <i class="fas fa-mobile-alt"></i>
          </div>
          <div class="security-info">
            <div class="security-title">手机号</div>
            <div class="security-desc">{{ maskPhone(userInfo.phone) }}</div>
          </div>
          <div class="security-action" @click="editField('phone')">修改</div>
        </div>
        
        <div class="security-item">
          <div class="security-icon">
            <i class="fas fa-lock"></i>
          </div>
          <div class="security-info">
            <div class="security-title">登录密码</div>
            <div class="security-desc">建议定期修改，保障账户安全</div>
          </div>
          <div class="security-action" @click="editField('password')">修改</div>
        </div>
        
        <div class="security-item">
          <div class="security-icon">
            <i class="fas fa-shield-alt"></i>
          </div>
          <div class="security-info">
            <div class="security-title">安全中心</div>
            <div class="security-desc">保障账户和资金安全</div>
          </div>
          <div class="security-action">
            <i class="fas fa-chevron-right setting-arrow"></i>
          </div>
        </div>
      </div>
      
      <!-- 生物识别设置 -->
      <div class="section-card">
        <div class="section-title">生物识别登录</div>
        
        <van-cell title="使用生物识别">
          <template #right-icon>
            <van-switch v-model="userSettings.useBiometric" size="24" @update:model-value="updateBiometricSettings" />
          </template>
        </van-cell>
        
        <div class="biometric-setup" v-if="userSettings.useBiometric">
          <div class="setup-title">选择使用的生物识别方式</div>
          <div class="biometric-options">
            <div 
              class="biometric-option" 
              :class="{'biometric-selected': userSettings.biometricType === 'fingerprint'}" 
              @click="selectBiometricType('fingerprint')"
            >
              <i class="fas fa-fingerprint biometric-icon"></i>
              <div class="biometric-name">指纹识别</div>
            </div>
            <div 
              class="biometric-option" 
              :class="{'biometric-selected': userSettings.biometricType === 'face'}" 
              @click="selectBiometricType('face')"
            >
              <i class="fas fa-user biometric-icon"></i>
              <div class="biometric-name">面部识别</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 通用设置部分 -->
      <div class="section-card">
        <div class="section-title">通用设置</div>
        
        <van-cell title="地址管理" is-link to="/address" />
        
        <van-cell title="消息通知">
          <template #right-icon>
            <van-switch v-model="userSettings.notifications" size="24" @update:model-value="updateNotificationSettings" />
          </template>
        </van-cell>
        
        <van-cell title="隐私设置" is-link @click="goToPrivacy" />
        
        <van-cell title="清除缓存" is-link @click="clearCache">
          <template #value>
            <span class="cache-size">{{ cacheSize }}</span>
          </template>
        </van-cell>
      </div>
      
      <!-- 退出登录按钮 -->
      <van-button class="logout-button" block @click="showLogoutConfirm">退出登录</van-button>
      
      <!-- 版本信息 -->
      <div class="version-info">
        宠物乐园 v1.0.0
      </div>
    </div>

    <!-- 底部弹出层 -->
    <van-popup v-model="showDatePicker" position="bottom" @closed="onPopupClosed">
      <van-date-picker
        title="选择生日"
        :min-date="minDate"
        :max-date="maxDate"
        :default-date="defaultDate"
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>

    <van-popup v-model="showGenderPicker" position="bottom" @closed="onPopupClosed">
      <van-picker
        title="选择性别"
        :columns="genderOptions"
        @confirm="onGenderConfirm"
        @cancel="showGenderPicker = false"
      />
    </van-popup>

    <van-dialog
      v-model="showInput"
      :title="dialogTitle"
      show-cancel-button
      @confirm="saveField"
      @cancel="showInput = false"
    >
      <van-field v-model="inputValue" :placeholder="inputPlaceholder" />
    </van-dialog>
    
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      style="display:none"
      @change="onFileChange"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showDialog, showLoadingToast, closeToast } from 'vant';
import type { PickerOption } from 'vant';
import api from '../network/api';

export default defineComponent({
  name: 'ProfileSettingsView',
  
  setup() {
    const router = useRouter();
    const loading = ref(false);
    const fileInput = ref<HTMLInputElement | null>(null);
    
    // 用户信息
    const userInfo = reactive({
      nickname: '',
      bio: '',
      gender: '',
      birthday: '',
      avatar: '',
      phone: ''
    });
    
    // 用户设置
    const userSettings = reactive({
      useBiometric: false,
      biometricType: 'fingerprint', // 'fingerprint' or 'face'
      notifications: true,
    });
    
    // 缓存大小
    const cacheSize = ref('0MB');
    
    // 状态控制
    const showDatePicker = ref(false);
    const showGenderPicker = ref(false);
    const showInput = ref(false);
    
    const dialogTitle = ref('');
    const inputValue = ref('');
    const inputPlaceholder = ref('');
    const currentField = ref('');
    
    // 日期范围
    const minDate = new Date(1950, 0, 1);
    const maxDate = new Date();
    const defaultDate = computed(() => {
      if (userInfo.birthday) {
        return new Date(userInfo.birthday);
      }
      return new Date(1990, 0, 15);
    });
    
    // 性别选项
    const genderOptions = [
      { text: '男', value: '男' },
      { text: '女', value: '女' },
      { text: '其他', value: '其他' }
    ] as PickerOption[];
    
    // 计算属性
    const genderText = computed(() => {
      const genderMap: {[key: string]: string} = {
        'male': '男',
        'female': '女',
        'other': '其他'
      };
      return genderMap[userInfo.gender] || '未设置';
    });

    // 获取用户信息
    const fetchUserProfile = async () => {
      try {
        loading.value = true;
        showLoadingToast({
          message: '加载中...',
          forbidClick: true,
        });
        
        const response = await api.getUserProfile();
        const responseData = response as any;
        
        // 检查是否有有效的用户数据
        if (responseData && responseData.code === 100 && responseData.data) {
          const profile = responseData.data;
          userInfo.nickname = profile.nickname || '';
          userInfo.bio = profile.bio || '';
          userInfo.gender = profile.gender || '';
          userInfo.birthday = profile.birthday || '';
          userInfo.avatar = profile.avatar || '';
          userInfo.phone = profile.phone || '';
          
          // 加载用户设置
          userSettings.useBiometric = Boolean(profile.useBiometric);
          userSettings.biometricType = profile.biometricType || 'fingerprint';
          userSettings.notifications = Boolean(profile.notificationsEnabled);
          
          // 加载缓存大小（模拟数据）
          fetchCacheSize();
        } else {
          // 如果接口没有返回有效数据，尝试从本地存储加载
          tryLoadFromLocalStorage();
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        // 尝试从本地存储加载
        tryLoadFromLocalStorage();
      } finally {
        loading.value = false;
        closeToast();
      }
    };
    
    // 尝试从本地存储加载用户信息
    const tryLoadFromLocalStorage = () => {
      try {
        const localUserInfo = localStorage.getItem('user_info');
        if (localUserInfo) {
          const userData = JSON.parse(localUserInfo);
          
          // 检查不同可能的数据结构
          if (userData.data) {
            // 如果是 { data: { ... } } 结构
            userInfo.nickname = userData.data.username || userData.data.nickname || '';
            userInfo.phone = userData.data.phone || '';
            if (userData.data.avatar) {
              userInfo.avatar = userData.data.avatar;
            }
          } else if (userData.username || userData.userId) {
            // 如果是直接的用户信息结构
            userInfo.nickname = userData.username || userData.nickname || '';
            userInfo.phone = userData.phone || '';
            if (userData.avatar) {
              userInfo.avatar = userData.avatar;
            }
          }
          
          console.log('从本地存储加载用户数据:', userInfo);
        } else {
          console.log('本地存储中没有用户信息');
        }
      } catch (e) {
        console.error('从本地存储加载数据失败:', e);
        showToast('获取用户信息失败');
      }
    };
    
    // 获取缓存大小（模拟）
    const fetchCacheSize = () => {
      // 模拟获取缓存大小，实际应该是从本地存储或后端获取
      const randomSize = (Math.random() * 100).toFixed(1);
      cacheSize.value = `${randomSize}MB`;
    };
    
    // 方法
    const goBack = () => {
      router.back();
    };
    
    const maskPhone = (phone: string) => {
      if (!phone) return '';
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    };
    
    // 打开日期选择器
    const openDatePicker = () => {
      console.log('打开日期选择器');
      showDatePicker.value = true;
    };
    
    // 打开性别选择器
    const openGenderPicker = () => {
      console.log('打开性别选择器');
      showGenderPicker.value = true;
    };
    
    // 弹窗关闭回调
    const onPopupClosed = () => {
      console.log('弹窗已关闭');
    };
    
    const onDateConfirm = async (date: Date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const newBirthday = `${year}-${month}-${day}`;
      
      try {
        showLoadingToast({
          message: '更新中...',
          forbidClick: true,
        });
        
        await api.updateUserProfile({ birthday: newBirthday });
        userInfo.birthday = newBirthday;
        showToast('生日信息更新成功');
      } catch (error) {
        showToast('更新生日信息失败');
        console.error('更新生日信息失败:', error);
      } finally {
        closeToast();
        showDatePicker.value = false;
      }
    };
    
    const onGenderConfirm = async (value: PickerOption) => {
      const genderMap: {[key: string]: string} = {
        '男': 'male',
        '女': 'female',
        '其他': 'other'
      };
      const newGender = genderMap[value.text as string] || 'other';
      
      try {
        showLoadingToast({
          message: '更新中...',
          forbidClick: true,
        });
        
        await api.updateUserProfile({ gender: newGender });
        userInfo.gender = newGender;
        showToast('性别信息更新成功');
      } catch (error) {
        showToast('更新性别信息失败');
        console.error('更新性别信息失败:', error);
      } finally {
        closeToast();
        showGenderPicker.value = false;
      }
    };
    
    const editField = (field: string) => {
      console.log('编辑字段:', field);
      currentField.value = field;
      
      switch (field) {
        case 'nickname':
          dialogTitle.value = '修改昵称';
          inputValue.value = userInfo.nickname;
          inputPlaceholder.value = '请输入昵称';
          break;
        case 'bio':
          dialogTitle.value = '修改个性签名';
          inputValue.value = userInfo.bio;
          inputPlaceholder.value = '请输入个性签名';
          break;
        case 'phone':
          dialogTitle.value = '修改手机号';
          inputValue.value = '';
          inputPlaceholder.value = '请输入新手机号';
          break;
        case 'password':
          dialogTitle.value = '修改密码';
          inputValue.value = '';
          inputPlaceholder.value = '请输入新密码';
          break;
      }
      
      showInput.value = true;
      console.log('对话框状态:', showInput.value);
    };
    
    const saveField = async () => {
      if (!inputValue.value.trim()) {
        showToast('输入不能为空');
        return;
      }
      
      try {
        showLoadingToast({
          message: '保存中...',
          forbidClick: true,
        });
        
        switch (currentField.value) {
          case 'nickname':
            await api.updateUserProfile({ nickname: inputValue.value });
            userInfo.nickname = inputValue.value;
            break;
          case 'bio':
            await api.updateUserProfile({ bio: inputValue.value });
            userInfo.bio = inputValue.value;
            break;
          case 'phone':
            // 简单的手机号验证
            if (!/^1[3-9]\d{9}$/.test(inputValue.value)) {
              showToast('请输入正确的手机号');
              closeToast();
              return;
            }
            await api.updateUserProfile({ phone: inputValue.value });
            userInfo.phone = inputValue.value;
            break;
          case 'password':
            // 这里应该调用修改密码API
            await api.updatePassword({ password: inputValue.value });
            break;
        }
        
        // 保存成功提示
        showToast('保存成功');
      } catch (error) {
        showToast('保存失败');
        console.error('保存失败:', error);
      } finally {
        closeToast();
        showInput.value = false;
      }
    };
    
    const uploadAvatarAction = () => {
      // 触发文件选择
      if (fileInput.value) {
        fileInput.value.click();
      }
    };
    
    const onFileChange = async (event: Event) => {
      const target = event.target as HTMLInputElement;
      if (target.files && target.files.length > 0) {
        const file = target.files[0];
        
        // 验证文件类型
        if (!file.type.includes('image/')) {
          showToast('请选择图片文件');
          return;
        }
        
        // 验证文件大小（限制为5MB）
        if (file.size > 5 * 1024 * 1024) {
          showToast('图片大小不能超过5MB');
          return;
        }
        
        try {
          showLoadingToast({
            message: '上传中...',
            forbidClick: true,
          });
          
          const formData = new FormData();
          formData.append('avatar', file);
          
          const response = await api.uploadAvatar(formData);
          const responseData = response as any;
          if (responseData.code === 100 && responseData.data && responseData.data.avatar_url) {
            userInfo.avatar = responseData.data.avatar_url;
            showToast('头像上传成功');
          }
        } catch (error) {
          showToast('头像上传失败');
          console.error('头像上传失败:', error);
        } finally {
          closeToast();
          // 重置文件输入框，以便再次选择同一文件
          if (fileInput.value) {
            fileInput.value.value = '';
          }
        }
      }
    };
    
    const selectBiometricType = async (type: string) => {
      try {
        showLoadingToast({
          message: '设置中...',
          forbidClick: true,
        });
        
        await api.updateUserSettings({
          biometric_type: type
        });
        
        userSettings.biometricType = type;
        showToast('设置已更新');
      } catch (error) {
        showToast('设置更新失败');
        console.error('设置更新失败:', error);
      } finally {
        closeToast();
      }
    };
    
    const updateBiometricSettings = async (value: boolean) => {
      try {
        showLoadingToast({
          message: '设置中...',
          forbidClick: true,
        });
        
        await api.updateUserSettings({
          use_biometric: value ? 1 : 0
        });
        
        showToast(value ? '已开启生物识别登录' : '已关闭生物识别登录');
      } catch (error) {
        // 恢复开关状态
        userSettings.useBiometric = !value;
        showToast('设置更新失败');
        console.error('设置更新失败:', error);
      } finally {
        closeToast();
      }
    };
    
    const updateNotificationSettings = async (value: boolean) => {
      try {
        showLoadingToast({
          message: '设置中...',
          forbidClick: true,
        });
        
        await api.updateUserSettings({
          notifications_enabled: value ? 1 : 0
        });
        
        showToast(value ? '已开启通知' : '已关闭通知');
      } catch (error) {
        // 恢复开关状态
        userSettings.notifications = !value;
        showToast('设置更新失败');
        console.error('设置更新失败:', error);
      } finally {
        closeToast();
      }
    };
    
    const goToPrivacy = () => {
      // 跳转到隐私设置页面
      router.push('/privacy');
    };
    
    const clearCache = () => {
      showDialog({
        title: '清除缓存',
        message: '确定要清除缓存吗？',
        showCancelButton: true
      })
      .then(async () => {
        // 清除缓存的逻辑
        try {
          showLoadingToast({
            message: '清除中...',
            forbidClick: true,
          });
          
          await api.clearUserCache();
          cacheSize.value = '0MB';
          showToast('缓存已清除');
        } catch (error) {
          showToast('清除缓存失败');
          console.error('清除缓存失败:', error);
        } finally {
          closeToast();
        }
      })
      .catch(() => {
        // 取消操作
      });
    };
    
    const showLogoutConfirm = () => {
      showDialog({
        title: '退出登录',
        message: '确定要退出当前账号吗？',
        showCancelButton: true
      })
      .then(async () => {
        // 退出登录
        try {
          showLoadingToast({
            message: '退出中...',
            forbidClick: true,
          });
          
          await api.logout();
          localStorage.removeItem('user_info');
          router.push('/login');
        } catch (error) {
          showToast('退出登录失败');
          console.error('退出登录失败:', error);
        } finally {
          closeToast();
        }
      })
      .catch(() => {
        // 取消操作
      });
    };
    
    // 页面初始化时获取用户数据
    onMounted(() => {
      console.log('ProfileSettingsView组件已加载');
      fetchUserProfile();
      
      // 添加事件监听器检查
      setTimeout(() => {
        console.log('当前状态检查:');
        console.log('- 对话框显示状态:', showInput.value);
        console.log('- 性别选择器显示状态:', showGenderPicker.value);
        console.log('- 日期选择器显示状态:', showDatePicker.value);
      }, 2000);
    });
    
    return {
      userInfo,
      userSettings,
      cacheSize,
      genderText,
      minDate,
      maxDate,
      defaultDate,
      genderOptions,
      showDatePicker,
      showGenderPicker,
      showInput,
      dialogTitle,
      inputValue,
      inputPlaceholder,
      fileInput,
      goBack,
      maskPhone,
      openDatePicker,
      openGenderPicker,
      onPopupClosed,
      onDateConfirm,
      onGenderConfirm,
      editField,
      saveField,
      uploadAvatarAction,
      onFileChange,
      selectBiometricType,
      updateBiometricSettings,
      updateNotificationSettings,
      goToPrivacy,
      clearCache,
      showLogoutConfirm
    };
  }
});
</script>

<style scoped>
.profile-settings-page {
  background-color: #f8fafc;
  min-height: 100vh;
  padding-top: 46px;
  padding-bottom: 30px;
}

.container {
  padding: 0 12px;
}

.section-card {
  background-color: white;
  margin: 15px 0;
  border-radius: 8px;
  overflow: hidden;
}

.section-title {
  padding: 15px;
  font-size: 16px;
  font-weight: 500;
  border-bottom: 1px solid #e2e8f0;
}

.security-item {
  display: flex;
  padding: 15px;
  align-items: center;
  border-bottom: 1px solid #e2e8f0;
}

.security-item:last-child {
  border-bottom: none;
}

.security-icon {
  width: 40px;
  height: 40px;
  background-color: #ebf8ff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
  color: #3490dc;
  font-size: 18px;
}

.security-info {
  flex: 1;
}

.security-title {
  font-size: 14px;
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 5px;
}

.security-desc {
  font-size: 12px;
  color: #718096;
}

.security-action {
  color: #3490dc;
  font-size: 14px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.bio-text {
  color: #718096;
  font-size: 14px;
  text-align: right;
}

.biometric-setup {
  background-color: #f7fafc;
  border-radius: 8px;
  padding: 15px;
  margin: 0 15px 15px;
}

.setup-title {
  font-size: 14px;
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 10px;
}

.biometric-options {
  display: flex;
  justify-content: space-around;
}

.biometric-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  background-color: white;
  width: 45%;
}

.biometric-selected {
  border-color: #3490dc;
  background-color: #ebf8ff;
}

.biometric-icon {
  font-size: 24px;
  color: #3490dc;
  margin-bottom: 10px;
}

.biometric-name {
  font-size: 12px;
  color: #4a5568;
}

.logout-button {
  margin: 30px 0;
  color: #e53e3e !important;
  font-size: 16px;
}

.version-info {
  text-align: center;
  padding: 20px 0;
  font-size: 12px;
  color: #a0aec0;
}

.cache-size {
  color: #718096;
}
</style> 